import random


def get_color():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))


def get_validCode_img(request):
    # 方式一 速度慢
    # img = Image.new(mode="RGB", size=(270, 40), color=get_color())
    # with open("static/img/validCode.png", "wb") as f:
    #     img.save(f, "png")
    # with open("static/img/validCode.png", "rb") as f:
    #     data = f.read()

    # 方式二 内存管理
    # from io import BytesIO
    # img = Image.new(mode="RGB", size=(270, 40), color=get_color())
    # f = BytesIO()
    # #保存到内存中了
    # img.save(f, "png")
    # #从内存中读取数据
    # data=f.getvalue()
    # 方式三：加文字
    from PIL import ImageDraw, ImageFont, Image
    from io import BytesIO
    img = Image.new(mode="RGB", size=(270, 40), color=get_color())
    # 在这个画板里画画
    draw = ImageDraw.Draw(img)
    # 字体样式
    font = ImageFont.truetype("static/font/春联标准行书体.ttf", 32)
    valid_code_str = ""
    # 生成随机字符
    for i in range(5):
        random_num = str(random.randint(0, 9))
        random_a = chr(random.randint(65, 90))
        random_b = chr(random.randint(95, 122))
        random_char = random.choice([random_num, random_a, random_b])

        draw.text((i * 50, 5), random_char, get_color(), font=font)
        # 保存验证码字符串
        valid_code_str += random_char
        # 存储在内存中的字节串
    # 验证码
    # print("valid_code_str", valid_code_str)

    request.session["valid_code_str"] = valid_code_str
    print(request.session.get("valid_code_str"))
    f = BytesIO()
    img.save(f, "png")
    data = f.getvalue()
    return data
